import React from 'react';
// 载入公共样式
import 'normalize.css/normalize.css';
import 'styles/base.less';
// 工具函数
import util from "commons/util";
import config from "commons/config";
import wxShare from "commons/wxShare";
import { tokenAvailable, tokenAvailableNew } from "api_xukaiyu/app/wechat";
import { isLogin, regGiftAmount } from "api_xukaiyu/app/login";
import { popup_list } from "api_xukaiyu/app/coupons";

import { Popup } from 'wd-mobile';

// 检测登录状态
const checkLogin = function () {
  isLogin().then(res => {
    window["hIsLogin"] = true;
    localStorage.setItem('UserId', res.data);

    let oldUserShow = localStorage.getItem('oldUserShow');
    if ((!oldUserShow || (new Date().getDate() != oldUserShow)) && (!location.href.includes('.html') || location.href.includes('index.html'))) {
      popup_list().then(data => {
        localStorage.setItem('oldUserShow',new Date().getDate());
        let clear = null;
        
        data.data&&data.data.length&&Popup.create({
          mask: true,
          maskStyle: { 'background': "rgba(0,0,0,.4)" },
          offset: { top: '5%', left: 0, right: 0 },
          content: <div className="oldDialog">
            <div className="redDialog">
              <div className="title">今日专享红包，购物折上折</div>
              <div className="awardList">
                {
                  data.data.map(item => {
                    return <div className="award" onClick={()=>{location.href="./category.html"}} key={item.couponId}>
                      <div className="money"><span hidden={item.cardType!=0}>¥</span>{item.cardType=='0'?item.amount:`${util.Mul(item.couponRatio,10)}折`}</div>
                      <div className="other">
                        <div className="name">{item.cardName}</div>
                        <div className="time">{item.pastDueTimeStr}</div>
                      </div>
                    </div>
                  })
                }
              </div>
              <div className="tips">红包卡券可以在“个人中心”“红包”查看</div>
            </div>
            <div className="close" onClick={() => clear()}></div>
          </div>,
          rootElement: document.querySelector('body')
        }, sender => {
          clear = sender.destroy;
        })
      })
    }

  }).catch(err => {
    window["hIsLogin"] = false;
    if (!sessionStorage.getItem('showNewRed') && !location.href.includes('invite.html') && !location.href.includes('login.html')) {
      regGiftAmount().then(data => {
        sessionStorage.setItem('showNewRed', true);
        let clear = null;
        Popup.create({
          mask: true,
          maskStyle: { 'background': "rgba(0,0,0,.4)" },
          offset: { top: '10%', left: 0, right: 0 },
          content: <div className="newRed">
            <div className="redDialog">
              <div className="tips">
                <div className="money">{data.data}<span>元</span></div>
                <div className="tipName">新用户福利</div>
                <div className="subTip">你有红包奖励等待领取</div>
              </div>
              <div className="getBtn" onClick={() => {
                location.href = './login.html';
              }}>现在领取</div>
            </div>
            <div className="close" onClick={() => clear()}></div>
          </div>,
          rootElement: document.querySelector('body')
        }, sender => {
          clear = sender.destroy;
        })
      })
    }
  })
}

checkLogin();

// 设置微信分享
wxShare();

/**
 * ES6 有一个特别规定，就是通过super调用父类的方法时，super会绑定子类的this。
 * http://es6.ruanyifeng.com/#docs/class#super-关键字
 */
class EntryBase extends React.Component {
  constructor(props) {
    super(props);

    this.state = {}

    // 微信授权配置
    this.wechatAuthorizeConfig = {
      appid: config.wechat.appId,
      redirect_uri: config.wechat.useAuthorize + util.joinQueryString({
        redirectUrl: location.href
      }),
      response_type: "code",
      scope: "snsapi_userinfo",
      state: config.wechat.appId
    };

    this.wechatToken = "";
  }

  componentDidMount() {
    util.checkWechatEnv((res) => {
      // 微信内
      if (res == "wechat") {
        //非小程序环境, 授权
        this.wxAuthorize();
      }
      if (res == 'miniprogram') {
        this.wxAuthorize();
      }
      // 微信外
      if (res == "outOfWechat") {
        //非微信环境, 根据配置决定是否授权
        if (!!config.wechat.notAllowdOutOfWechat) {
          this.wxAuthorize();
        }
      }
    })
  }

  componentWillUnmount() { }

  // 验证微信token
  wxAuthorize() {
    return new Promise((resolve, reject) => {
      const queryObject = util.parseQueryString();
      let wechatTokenFromUrl = queryObject.token;
      let wechatTokenFromLocal = localStorage.getItem("wechatToken");
      const token = wechatTokenFromUrl || wechatTokenFromLocal; // 优先使用url的token
      if (token) {
        // 如果url或者localStorage里有token, 验证有效性。如果无效：跳转授权。如果有效：继续登录
        tokenAvailableNew({
          token: token
        }).then(res => {
          localStorage.setItem("wechatToken", token);
          this.wechatToken = token;
          resolve({
            isOld: !!(+res.data),
            isFlagState: !!(+res.data)
          })
        }).catch(res => {
          location.replace("https://open.weixin.qq.com/connect/oauth2/authorize" + util.joinQueryString(this.wechatAuthorizeConfig));
        })
      } else {
        // 如果都没有，跳转授权
        location.replace("https://open.weixin.qq.com/connect/oauth2/authorize" + util.joinQueryString(this.wechatAuthorizeConfig));
      }
    })
  }
}

export default EntryBase;